package com.hospital.dao;

import com.hospital.model.QueueRecord;
import com.hospital.model.Department;
import com.hospital.model.Doctor;
import com.hospital.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class QueueRecordDAO {
    
    public String generateQueueNumber(Integer departmentId, Integer doctorId) {
        String sql = "SELECT COUNT(*) as count FROM queue_record " +
                    "WHERE department_id = ? AND doctor_id = ? " +
                    "AND DATE(created_at) = CURRENT_DATE";
        
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, departmentId);
            stmt.setInt(2, doctorId);
            rs = stmt.executeQuery();
            
            if (rs.next()) {
                int count = rs.getInt("count") + 1;
                return String.format("%02d%02d%03d", departmentId, doctorId, count);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeAll(conn, stmt, rs);
        }
        
        return null;
    }
    
    public boolean create(QueueRecord record) {
        String sql = "INSERT INTO queue_record (patient_name, patient_phone, department_id, doctor_id, " +
                    "queue_number, status) VALUES (?, ?, ?, ?, ?, ?)";
        
        Connection conn = null;
        PreparedStatement stmt = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, record.getPatientName());
            stmt.setString(2, record.getPatientPhone());
            stmt.setInt(3, record.getDepartmentId());
            stmt.setInt(4, record.getDoctorId());
            stmt.setString(5, record.getQueueNumber());
            stmt.setInt(6, record.getStatus());
            
            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.closeAll(conn, stmt, null);
        }
    }
    
    public QueueRecord findCurrentByDoctor(Integer doctorId) {
        String sql = "SELECT q.*, d.name as dept_name, d.description as dept_description, " +
                    "doc.name as doc_name, doc.title as doc_title " +
                    "FROM queue_record q " +
                    "JOIN department d ON q.department_id = d.id " +
                    "JOIN doctor doc ON q.doctor_id = doc.id " +
                    "WHERE q.doctor_id = ? AND q.status = 1 " +
                    "AND DATE(q.created_at) = CURRENT_DATE";
        
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, doctorId);
            rs = stmt.executeQuery();
            
            if (rs.next()) {
                return mapResultSetToQueueRecord(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeAll(conn, stmt, rs);
        }
        
        return null;
    }
    
    public List<QueueRecord> findWaitingByDoctor(Integer doctorId) {
        List<QueueRecord> records = new ArrayList<>();
        String sql = "SELECT q.*, d.name as dept_name, d.description as dept_description, " +
                    "doc.name as doc_name, doc.title as doc_title " +
                    "FROM queue_record q " +
                    "JOIN department d ON q.department_id = d.id " +
                    "JOIN doctor doc ON q.doctor_id = doc.id " +
                    "WHERE q.doctor_id = ? AND q.status = 0 " +
                    "AND DATE(q.created_at) = CURRENT_DATE " +
                    "ORDER BY q.created_at";
        
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, doctorId);
            rs = stmt.executeQuery();
            
            while (rs.next()) {
                records.add(mapResultSetToQueueRecord(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeAll(conn, stmt, rs);
        }
        
        return records;
    }
    
    public boolean updateStatus(Integer id, Integer status) {
        String sql = "UPDATE queue_record SET status = ?, ";
        if (status == 1) {
            sql += "called_at = CURRENT_TIMESTAMP";
        } else if (status == 2) {
            sql += "completed_at = CURRENT_TIMESTAMP";
        }
        sql += " WHERE id = ?";
        
        Connection conn = null;
        PreparedStatement stmt = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, status);
            stmt.setInt(2, id);
            
            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.closeAll(conn, stmt, null);
        }
    }
    
    private QueueRecord mapResultSetToQueueRecord(ResultSet rs) throws SQLException {
        QueueRecord record = new QueueRecord();
        record.setId(rs.getInt("id"));
        record.setPatientName(rs.getString("patient_name"));
        record.setPatientPhone(rs.getString("patient_phone"));
        record.setDepartmentId(rs.getInt("department_id"));
        record.setDoctorId(rs.getInt("doctor_id"));
        record.setQueueNumber(rs.getString("queue_number"));
        record.setStatus(rs.getInt("status"));
        record.setCreatedAt(rs.getTimestamp("created_at"));
        record.setCalledAt(rs.getTimestamp("called_at"));
        record.setCompletedAt(rs.getTimestamp("completed_at"));
        
        Department dept = new Department();
        dept.setId(rs.getInt("department_id"));
        dept.setName(rs.getString("dept_name"));
        dept.setDescription(rs.getString("dept_description"));
        record.setDepartment(dept);
        
        Doctor doctor = new Doctor();
        doctor.setId(rs.getInt("doctor_id"));
        doctor.setName(rs.getString("doc_name"));
        doctor.setTitle(rs.getString("doc_title"));
        record.setDoctor(doctor);
        
        return record;
    }
}